<template>
	<view class="container">
		<button @click="handleChooseImage">选择图片</button>
		<image v-if="imageUrl" :src="imageUrl" mode="aspectFit"></image>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	// 存储图片 URL 的响应式变量
	const imageUrl = ref('');

	// 选择图片的函数
	const handleChooseImage = () => {
		uni.chooseImage({
			count: 1,
			success: (res) => {
				const tempFilePaths = res.tempFilePaths;
				uploadImage(tempFilePaths[0]);
			}
		});
	};

	const $emit = defineEmits(['imageUploaded'])

	// 上传图片的函数
	const uploadImage = (filePath) => {
		// 替换为云服务器的公网 IP 或域名
		// const serverUrl = 'https://www.zglzgl.icu';
		const serverUrl = 'http://175.178.118.46:3000'
		uni.uploadFile({
			url: `${serverUrl}/upload`,
			filePath: filePath,
			name: 'image',
			success: (res) => {
				console.log(res, '22222222')
				const data = JSON.parse(res.data);
				imageUrl.value = data.imageUrl;
				$emit('imageUploaded', data.imageUrl)
			},
			fail: (err) => {
				console.error('上传失败:', err);
			}
		});
	};
</script>

<style>
	.container {
		padding: 20px;
		text-align: center;
	}
</style>